package 学习计划.数据结构;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 会玩的洋洋
 * https://leetcode.cn/problems/subarray-sum-equals-k/?envType=study-plan&id=shu-ju-jie-gou-ji-chu&plan=data-structures&plan_progress=cqjfoh6
 */
public class _560_和为K的子数组 {
    /**
     * 暴力解法
     * 执行用时：1806ms，内存消耗：44.8MB
     * @param nums
     * @param k
     * @return
     */
    public int subarraySum(int[] nums, int k) {
        int n = nums.length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int temp = 0;
            for (int j = i; j < n; j++) {
                temp += nums[j];
                if (temp == k) {
                    ans++;
                }
            }
        }
        return ans;
    }

    /**
     * 执行用时：23ms，内存消耗：45.9MB
     * @param nums
     * @param k
     * @return
     */
    public int subarraySum2(int[] nums, int k) {
        int count = 0, pre = 0;
        Map<Integer, Integer> mp = new HashMap<>();
        mp.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i];
            if (mp.containsKey(pre - k)) {
                count += mp.get(pre - k);
            }
            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
